<?php
// 应用公共文件
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\model\Collection;
use think\response\Json;

/**
 * 统一返回接口格式
 * @param int $code
 * @param string $message
 * @param array|string|Collection $data
 * @return Json
 */
function apiResponse(int $code, string $message = "success", array|string|Collection $data = []): Json
{
    return json(['code' => $code, 'message' => $message, 'data' => $data]);
}

/**
 * 统一模型返回格式
 * @param int $code
 * @param string $message
 * @param array|string|Collection $data
 * @return array
 */
function modelResponse(int $code, string $message = "success", array|string|Collection $data = []): Array
{
    return ['code' => $code, 'message' => $message, 'data' => $data];
}

/**
 * 生成token
 * @param $payload
 * @return string
 */
function generateToken($payload): string
{
    $config = config('jwt');
    return JWT::encode($payload, $config['secret'], $config['algorithm']);
}

/**
 * token校验
 * @param $token
 * @return Json|string
 */
function verifyToken($token): Json|string
{
    $config = config('jwt');
    try {
        JWT::decode($token, new Key($config['secret'], $config['algorithm']));
        return false;
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}